$(document).ready(function() {
	
	if (!stringIsNull($('#errorMessage').val())) {
		showErrorNoticeMessage($('#errorMessage').val());
	}
	
	if (!stringIsNull($('#successMessage').val())) {
		showSuccessNoticeMessage($('#successMessage').val());
	}
	var page_res_id = $('#page_res_id').val();
	//保存
	$("form").submit(function() {
		var data = $("form").serialize();
		var d = [];
		var trs = $('table.mtable tr');
		for (var i=1;i<trs.length;i++) {
			var ipts = trs.eq(i).find("input");
			var dd = [];
			for (var j=0;j<ipts.length;j++) {
				if (ipts[j]!=undefined) {
					if (ipts[j].value!=undefined) {
						dd.push(ipts[j].value);
					}
				}
			}
			d.push(dd);
		}
		
		d = JSON.stringify(d).replace(/"/g,"'");
		
		data = data+"&uDefinedDataFormMap.udefined_data="+d;
		
		$.post(rootPath + "/workcenter_model/user_defined_data/saveUserDefinedData.shtml", data, function(e, status, xhr){
			var data= JSON.parse(e);
			if (data.status) {
				showSuccessNoticeMessage("自定义数据保存成功");
			}else {
				showErrorNoticeMessage(data.message);
			}
		},"json")
		return false;
	});
	
	//检索
	$('#btnQuery').click(function (){
		var data_type = $('#data_type').val();
		var tb = $(".index_centent");
		tb.empty();
		tb.load(rootPath + "/workcenter_model/user_defined_data/queryUserDefinedData.shtml?data_type="+data_type+"&page_res_id="+page_res_id);
	})
	
	//清除
	$('#btnClear').click(function (){
		var tb = $(".index_centent");
		tb.empty();
		tb.load(rootPath + "/workcenter_model/user_defined_data/udefined_data_maintenance.shtml?page_res_id="+page_res_id);
	})
	
	//插入新行
	$('#tb_add').click(function (){
		var num = 10;
		var trs = $('#udefinedTable tr');
		for (var i=1;i<trs.length;i++) {
			var td = trs.eq(i).find("input:first");
			if (td[0]!=undefined) {
				if (td[0].value!=undefined && parseInt(td[0].value)>=num) {
					num = parseInt(td[0].value) + 10;
				}
			}
		}
		var newRow = "<tr><td><input type='text' validate_datatype='number_int' validate_errormsg='顺序必须为数字' value="+num+"></td>" +
				"<td><input type='text' validate_allowedempty='N' validate_errormsg='数据字段key不能为空！' ></td>" +
				"<td><input type='text' validate_allowedempty='N' validate_errormsg='字段标签不能为空！' ></td></tr>";
		$.MTable.addRow("udefinedTable",newRow);
	})
	
	//删除选定行
	$('#tb_del').click(function (){
		$.MTable.delCheckRow("udefinedTable");
	})
	
	//删除全部行
	$('#tb_delAll').click(function (){
		$.MsgBox.Confirm("系统提示","该操作会清空下列所有行，确定继续吗？",function (){
			$.MTable.delAll("udefinedTable");
		});
	})
})